<!-- 养殖批次 -->
<template>
    <el-dialog :close-on-click-modal="false"  ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="50%"
        :before-close="handleClose">
        <el-form id="guide_form" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px"
            class="demo-ruleForm">
            <el-form-item label="批次名称" prop="batchName">
                <el-input v-model="ruleForm.batchName" class="w100p" placeholder="请输入批次名称"></el-input>
            </el-form-item>
            <el-form-item label="批次号" prop="batchCode">
                <el-input disabled v-model="ruleForm.batchCode" class="w100p" placeholder="请输入批次号"></el-input>
            </el-form-item>
            <el-form-item label="设施名称" prop="facilityId">
                <el-select class="w100p" v-model="ruleForm.facilityId" clearable filterable placeholder="请选择设施名称"
                    @change="queryBatchPondRatio">
                    <el-option v-for="(item, index) in facilityList" :key="index" :label="item.facilityName"
                        :value="item.facilityId" />
                </el-select>
            </el-form-item>
            <el-form-item label="清塘同步完成" prop="clearCompleteFlag">
                <el-select class="w100p" v-model="ruleForm.clearCompleteFlag" clearable filterable
                    placeholder="请选择是否清塘同步完成">
                    <el-option label="否" :value="false" />
                    <el-option label="是" :value="true" />
                </el-select>
            </el-form-item>
            <el-form-item label="养殖占比" prop="pondRatio">
                <div class="flex">
                    <el-input type="number" class="w100p" v-model="ruleForm.pondRatio" placeholder="请输入占比">
                        <template slot="append">%</template>
                    </el-input>
                    <el-button @click="adjustPondRatio">调整占比</el-button>
                </div>
                <div v-if="addEditFlag == 'add'">剩余占比：{{ remainingRatio }}%</div>
            </el-form-item>
            <el-form-item label="创建日期" prop="buildDate">
                <el-date-picker class="w100p" type="date" placeholder="选择日期" v-model="ruleForm.buildDate"
                    :picker-options="pickerOptions"></el-date-picker>
            </el-form-item>
            <el-row :gutter="10" v-for="item, index in ruleForm.batchDetailList" :key="index">
                <el-col :span="12">
                    <el-form-item :label="index == 0 ? '养殖品种' : ''" :prop="`batchDetailList[${index}][plantVarietyId]`"
                        :rules="rules.plantVarietyId">
                        <el-select class="w100p" v-model="item.plantVarietyId" clearable filterable
                            placeholder="请选择养殖品种" @change="(e) => { handleChangePlantVariety(e, index) }">
                            <el-option v-for="item, index in parentId ? childrenVarietyList : varietyList" :key="index"
                                :label="item.plantVarietyName" :value="item.plantVarietyId"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item :label="index == 0 ? '养殖数量(目标)' : ''" :prop="`batchDetailList[${index}][num]`"
                        :rules="rules.num">
                        <el-input type="number" v-model="item.num" placeholder="请输入参数">
                            <template slot="append">粒</template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item :label="index == 0 ? '养殖重量(目标)' : ''" :prop="`batchDetailList[${index}][weight]`"
                        :rules="rules.weight">
                        <el-input type="number" v-model="item.weight" placeholder="请输入参数">
                            <template slot="append">斤</template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="3" class="iconList">
                    <i class="icon el-icon-circle-plus-outline" @click.stop="addMaterial()"></i>
                    <i v-show="ruleForm.batchDetailList.length > 1" class="icon el-icon-remove-outline"
                        @click.stop="delMaterial(index)"></i>
                </el-col>
            </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm" id="guide_form_add">确 定</el-button>
        </span>
        <pondRatio :facilityId="facilityId" :dialogVisible="isShowPondRatio" @closeDialog="closeDialog"
            @getRemainingRatio="getRemainingRatio"></pondRatio>
        <div class="guideBox" v-if="isGuide">
            <div class="routerInfo" :style="guideStyle"
                v-if="isGuide && guideInfo.index > 0 && guideInfo.procedure.length">
                <div class="guideText">{{ guideIndex + 1 }}. {{ guideInfo.procedure && guideInfo.procedure.length >
                    0 ?
                    guideInfo.procedure[guideIndex]
                    : '' }}</div>
                <div class="guideNext" @click="guideNext" v-if="guideInfo.procedure.length > (guideIndex + 1)">下一步
                </div>
            </div>
        </div>
    </el-dialog>
</template>
<script>
import batch from '@/api/batch/batchManagement';
import batchDetail from '@/api/batch/batchDetail';
import pondRatio from './pondRatio';

export default {
    components: { pondRatio },
    computed: {
        guideInfo() {
            return this.$store.state.user.guideInfo;
        },
        isGuide() {
            return this.$store.state.user.isGuide || ''
        },
    },
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        parentId: null,
        batchType: {
            type: String,
            default: () => {
                return ''
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        facilityList: {
            type: Array,
            default: () => {
                return []
            }
        },
        varietyList: {
            type: Array,
            default: () => {
                return []
            }
        }
    },
    data() {
        let validatorNumber = function (rule, value, callback) {
            if (value > 0 && Number(value || 0) % 1 == 0) {
                callback()
            } else {
                callback(new Error('请输入大于0的整数值！'))
            }
        }
        let validatorWeight = function (rule, value, callback) {
            if (value > 0) {
                callback()
            } else {
                callback(new Error('请输入大于0的数值！'))
            }
        }
        let validatorPondRatio = function (rule, value, callback) {
            if (value > 0 && value <= 100) {
                callback()
            } else {
                callback(new Error('请输入大于0小于100的数值！'))
            }
        }
        return {
            guideIndex: 0,
            guideStyle: {},
            addEditName: '添加',
            addEditApi: batch.add,
            isShowPondRatio: false,
            ruleForm: {},
            facilityId: '',
            childrenVarietyList: [],
            batchList: [],
            remainingRatio: 0,
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            rules: {
                batchName: [
                    { required: true, message: '请输入批次名称', trigger: 'change' }
                ],
                facilityId: [
                    { required: true, message: '请选择设施', trigger: 'change' }
                ],
                batchCode: [
                    { required: true, message: '请输入助记码', trigger: 'change' }
                ],
                plantVarietyId: [
                    { required: true, message: '请选择品种', trigger: 'change' }
                ],
                num: [
                    { required: true, validator: validatorNumber, trigger: 'change' }
                ],
                weight: [
                    { required: true, validator: validatorWeight, trigger: 'change' }
                ],
                buildDate: [
                    { required: true, message: '请选择日期', trigger: 'blur' }
                ],
                pondRatio: [
                    { required: true, validator: validatorPondRatio, trigger: 'blur' }
                ],
                clearCompleteFlag: [
                    { required: true, message: '请选择是否同步完成', trigger: 'change' }
                ],
            }
        }
    },

    watch: {
        guideInfo: {
            handler(v) {
                this.setGuide(v)
                console.log(v)
            },
            deep: true
        },
        dialogVisible(v) {
            v && this.initData()
        }
    },

    mounted() { },
    methods: {
        initData() {
            if (this.addEditFlag == 'add') {
                this.ruleForm = {}
                this.resetForm()
                this.addEditApi = batch.add
                this.addEditName = '添加';
                this.$set(this.ruleForm, 'batchType', this.batchType); //批次类型标识
                this.$set(this.ruleForm, 'clearCompleteFlag', false); //清塘同步完成
                this.$set(this.ruleForm, 'status', 'CREATE'); //新创建
                this.$set(this.ruleForm, 'facilityId', this.facilityList.length > 0 ? this.facilityList[0].facilityId : '');
                this.$set(this.ruleForm, 'batchDetailList', [{
                    weight: null, num: null, plantVarietyId: null, plantVarietyName: null
                }])
                this.addcode();
                setTimeout(() => {
                    this.setGuide(this.guideInfo || {})
                }, 500);
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = { ...this.data }
                this.$set(this.ruleForm, 'clearCompleteFlag', this.data.clearCompleteFlag ? true : false); //清塘同步完成
                this.addEditApi = batch.edit
                this.addEditName = '编辑';
                this.queryBatchPondRatio(this.data.facilityId)
            }
            this.$set(this.ruleForm, 'batchType', this.batchType); //批次类
            console.log(this.data.batchId, '-----------------')
            this.queryByCondition(this.data.batchId);
            this.queryParentDataList(this.parentId);
        },
        guideNext() {
            let { index, procedure } = this.guideInfo;
            this.$store.dispatch("user/getGuideInfo", {
                procedure: procedure,
                index: index + 1
            });
        },
        setGuide(v) {
            if (!this.isGuide) return;
            let { index } = v;
            this.guideIndex = index;
            let btn = document.getElementById('guide_form_add');
            let formDom = document.getElementById('guide_form');
            console.log(formDom, btn, index)
            this.resetGuide(formDom);
            this.resetGuide(btn);
            if (index == 2) {
                formDom&&(formDom.className += " guide-name");
                this.guideStyle = {
                    top: '12%',
                    right: '29%',
                    wayFlag: 'right'
                }
            } else if (index == 3) {
                btn&&(btn.className += " guide-name");
                this.guideStyle = {
                    top: '60%',
                    right: '33%',
                    wayFlag: 'right'
                }
            } else {
                this.resetForm(); this.cancel()
            }
        },

        resetGuide(node) {
            node&&(node.className = node.className.replace("guide-name", ""))
        },
        adjustPondRatio() {
            this.facilityId = this.ruleForm.facilityId;
            this.isShowPondRatio = true
        },
        handleChangePlantVariety(e, index) {
            console.log(e, index)
            let plantVarietyName = this.$public.foundObject(this.varietyList, 'plantVarietyId', e).plantVarietyName || '';
            this.$set(this.ruleForm.batchDetailList[index], 'plantVarietyName', plantVarietyName)
            console.log(plantVarietyName)
        },
        async addcode() {
            let res = await batchDetail.addcode();
            this.$set(this.ruleForm, 'batchCode', res.data); //批次类型标识
        },
        getRemainingRatio(ratio) {
            this.remainingRatio = ratio;
            if (this.ruleForm.pondRatio && this.ruleForm.pondRatio > this.remainingRatio) {
                this.ruleForm.pondRatio = 0;
            }
            console.log(this.ruleForm.batchId)
            if (this.ruleForm.batchId) {
                this.queryBatch(this.ruleForm.batchId)
            }
        },
        queryBatchPondRatio(facilityId) {
            batch.queryByCondition({ batchType: 'BREEDING', facilityId }).then(res => {
                this.batchList = res.data || [];
                this.computationPondRatio()
            })
        },
        queryBatch(batchId) {
            batch.queryById(batchId).then(res => {
                console.log(res.data)
                let data = res.data || {}
                this.ruleForm = {
                    ...this.ruleForm,
                    ...data
                }
                this.queryByCondition(batchId)
                this.queryParentDataList(this.parentId)
            })
        },
        //计算占比
        computationPondRatio() {
            let ratio = this.batchList.reduce((accumulator, currentObject) => {
                return accumulator + currentObject.pondRatio;
            }, 0);
            this.remainingRatio = 100 - ratio
        },
        addMaterial() {
            let length = this.ruleForm.batchDetailList?.length || 0
            if (length) {
                this.$set(this.ruleForm.batchDetailList, length, {
                    weight: null, num: null, plantVarietyId: null, plantVarietyName: null
                })
            }
        },
        async delMaterial(index) {
            let batchDetailId = this.ruleForm.batchDetailList[index].batchDetailId || null;
            if (this.addEditFlag == 'edit' && this.ruleForm.batchDetailList.filter(item => { return item.batchDetailId }).length == 1 && batchDetailId) {
                this.$message.warning('只是保留一个养殖品种')
                return
            }

            let isDel = true;
            if (this.addEditFlag == 'edit' && batchDetailId) {
                let res = await batchDetail.delList(batchDetailId);
                this.$message[res.code == 1 ? 'success' : 'warning'](res.code == 1 ? '删除成功' : '删除失败')
                isDel = res.code == 1;
            }
            if (isDel) {
                let list = this.ruleForm.batchDetailList;
                list.splice(index, 1);
                this.$set(this.ruleForm, 'batchDetailList', list);
            };
            if (!this.ruleForm.batchDetailList || this.ruleForm.batchDetailList.length == 0) {
                this.$set(this.ruleForm, 'batchDetailList', [{
                    weight: null, num: null, plantVarietyId: null, plantVarietyName: null
                }])
            }
        },
        //提交表单
        submitForm() {
            console.log(this.ruleForm);
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    this.addEditApi({ ...this.ruleForm, parentId: this.parentId }).then(res => {
                        this.$message[res.code == 1 ? 'success' : 'warning'](res.code == 1 ? '操作成功' : res.msg)
                        res.code == 1 && this.cancel();
                        // let batchId = res.data.batchId;
                        // let promiseAllList = []
                        // this.ruleForm.batchDetailList.forEach(item => {
                        //     if (item.batchDetailId) {
                        //         promiseAllList.push(this.editbatchDetail(item))
                        //     } else {
                        //         promiseAllList.push(this.addbatchDetail(batchId, item))
                        //     }
                        // });
                        // Promise.all(list).then(resList => {
                        //     console.log(resList);
                        //     this.cancel();
                        // }).catch(errList => {
                        //     this.cancel();
                        //     console.log(errList)
                        // });
                    }).catch(err => {
                        console.log(err)
                    })
                } else {
                    return false;
                }
            })
        },
        async addbatchDetail(batchId, param) {
            return batchDetail.add({ batchId: batchId, ...param });
        },
        async editbatchDetail(param) {
            return batchDetail.edit({ ...param });
        },
        async delbatchDetail(batchDetailId) {
            if (batchDetailId) {

            }
        },
        async queryParentDataList(batchId) {
            console.log(batchId)
            if (!batchId) return;
            this.childrenVarietyList = [];
            let { data } = await batchDetail.queryByCondition({ batchId });
            let dataList = data || []
            let varietyObj = {}
            dataList.forEach(item => {
                varietyObj[item.plantVarietyId] = item.plantVarietyId
            })
            for (let key in varietyObj) {
                this.childrenVarietyList.push(this.varietyList.find(item => { return item.plantVarietyId == key }))
            }
            if (dataList.length == 0) {
                this.$set(this.ruleForm, 'batchDetailList', [
                    { weight: null, num: null, plantVarietyId: null, plantVarietyName: null }
                ])
            }
        },
        async queryByCondition(batchId) {
            console.log(batchId)
            if (!batchId) return;
            let { data } = await batchDetail.queryByCondition({ batchId });
            let dataList = data || []
            if (dataList.length == 0) {
                this.$set(this.ruleForm, 'batchDetailList', [
                    { weight: null, num: null, plantVarietyId: null, plantVarietyName: null }
                ])
            } else {
                this.$set(this.ruleForm, 'batchDetailList', dataList);
            }
        },
        //重置
        resetForm() {
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭 
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        },
        //关闭弹窗
        closeDialog() {
            this.isShowPondRatio = false;
        },
    }
};
</script>
<style lang="scss" scoped>
.icon {
    font-size: 20px;
    line-height: 29px;
    cursor: pointer;
}

.flex {
    display: flex;
}

.guideBox {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #00000030;
    z-index: 10;
}

.routerInfo {
    max-width: 400px;
    min-width: 300px;
    padding: 10px;
    background-color: #FF9243;
    color: #ffffff;
    position: fixed;
    z-index: 9999;

    .guideText {
        width: 100%;
        text-align: left;
        line-height: 26px;
    }

    .guideNext {
        width: 100px;
        margin-top: 15px;
        background-color: #e4a579;
        border: 1px solid #c65504;
        border-radius: 4px;
        text-align: center;
        line-height: 28px;
        cursor: pointer;

        &:hover {
            background-color: #d88244;
        }
    }
}

::v-deep {

    .el-table--border::after,
    .el-table--group::after,
    .el-table::before {
        z-index: 0;
    }

    .el-checkbox__inner {
        z-index: 0;
    }
}

#guide_form {
    background-color: #ffffff;
}
</style>